package com.bidevalution.business.impl;

import com.bidevalution.business.dto.VoteResultDto;
import com.bidevalution.business.service.BeExpertVoteResultService;
import com.bidevalution.dao.entity.*;
import com.bidevalution.dao.mapper.*;
import com.bidevalution.support.context.Constants;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.GsonUtil;
import com.qtp.core.util.IdsUtil;

import com.qtp.core.util.OConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by glodon on 2019-08-15.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BeExpertVoteResultServiceImpl implements BeExpertVoteResultService {
    @Autowired
    private BeExpertVoteResultMapper beExpertVoteResultMapper;
    @Autowired
    private BeSectionExpertInfoMapper beSectionExpertInfoMapper;
    @Autowired
    private BeSectionExpertProgressMapper beSectionExpertProgressMapper;
    @Autowired
    private BeSectionMethodMapper beSectionMethodMapper;
    @Autowired
    private BeSectionInfoMapper beSectionInfoMapper;


    /**
     * 专家投票推选组长
     *
     * @param sectionId
     * @return
     * @throws Exception
     */
    @Override
    public Boolean voteExpert(String expertId, String sectionId, String voteResult, String sectionStepId, String voteType, int flag) throws Exception {
        //查询当前标段流程的版本号submitCode
        BeSectionMethod beSectionMethod = beSectionMethodMapper.selectByPrimaryKey(sectionId);
        String submitCode = null;
        //if ("2".equals(voteType)) {
            submitCode = beSectionMethod.getSubmitCode();
       // }
        BeExpertVoteResult beExpertVoteResultv = beExpertVoteResultMapper.selectByExpertId(sectionId, expertId, voteType, submitCode);
        if ( beExpertVoteResultv != null) {
            if(voteType.equals("1")){
                throw new Exception("您已经投票");
            }else if(voteType.equals("2")){
                throw new Exception("您已经投票");
            }else{
                throw new Exception("您已推荐过组长");
            }

        }
        BeExpertVoteResult beExpertVoteResult = new BeExpertVoteResult();
        beExpertVoteResult.setSectionId(sectionId);
        beExpertVoteResult.setSeqId(IdsUtil.uuid());
        beExpertVoteResult.setExpertId(expertId);
        beExpertVoteResult.setVoteResult(voteResult);
        beExpertVoteResult.setVoteType(voteType);
        beExpertVoteResult.setSubmitCode(beSectionMethod.getSubmitCode());
        beExpertVoteResult.setCreateTime(new Date());
        beExpertVoteResult.setUpdateTime(new Date());
        if (beExpertVoteResultMapper.insert(beExpertVoteResult) < 1) {
            throw new Exception("推选组长失败");
        }
        if ("0".equals(voteType)) {
            BeSectionExpertInfo _beSectionExpertInfo = beSectionExpertInfoMapper.selectByPrimaryKey(expertId);
            BeSectionExpertProgressKey beSectionexpertProgressKey = new BeSectionExpertProgressKey();
            beSectionexpertProgressKey.setExpertId(_beSectionExpertInfo.getSeqId());
            beSectionexpertProgressKey.setSectionStepId(sectionStepId);
            BeSectionExpertProgress beSectionExpertProgress = beSectionExpertProgressMapper.selectByPrimaryKey(beSectionexpertProgressKey);
            if (beSectionExpertProgress == null) {
                throw new Exception("专家评审环节不存在");
            }
            beSectionExpertProgress.setIsFinish("1");
            beSectionExpertProgressMapper.updateByPrimaryKey(beSectionExpertProgress);

            //判断是否所有专家都已投票完毕,且没有重复票数，更新是否组长标识
            if (isAllExpertVoted(sectionId, voteType, flag)) {
                //找出得票做多的
                Map<String, Object> maxVotedResult = beExpertVoteResultMapper.getMaxVotedExpert(sectionId);
                if(maxVotedResult != null && !maxVotedResult.isEmpty()) {
                    String maxVoteResult = OConvertUtils.getString(maxVotedResult.get("vote_result"));
                    //更新组长状态
                    BeSectionExpertInfo beSectionExpertInfo = new BeSectionExpertInfo();
                    beSectionExpertInfo.setSeqId(maxVoteResult);
                    beSectionExpertInfo.setIsManager(Constants.ONE);
                    beSectionExpertInfoMapper.updateByPrimaryKeySelective(beSectionExpertInfo);
                }
            }
        }
        return true;
    }

    /**
     * 查询当前账号推选结果
     *
     * @param sectionId
     * @return
     * @throws Exception
     */
    @Override
    public BeExpertVoteResult getBeExpertVoteResult(String expertId, String sectionId, String voteType) throws Exception {
    	 BeSectionMethod beSectionMethod = beSectionMethodMapper.selectByPrimaryKey(sectionId);
         String submitCode = beSectionMethod.getSubmitCode();
         
        return beExpertVoteResultMapper.selectByExpertId(sectionId, expertId, voteType, submitCode);
    }

    /**
     * 查询当前标段的投标结果
     *
     * @param sectionId
     * @return
     * @throws Exception
     */
    @Override
    public List<VoteResultDto> getVoteResultList(String sectionId, String voteType) throws Exception {
        List<Map<String, String>> list = beExpertVoteResultMapper.getVoteResultList(sectionId, voteType);
        return GsonUtil.parseJsonArrayWithGson(GsonUtil.toJson(list), VoteResultDto.class);
    }

    /**
     * 判断是否所有专家投票完成，且没有重复
     *
     * @param sectionId
     * @return
     * @throws Exception
     */
    private Boolean isAllExpertVoted(String sectionId, String voteType, int flag) throws Exception {
        if (beSectionExpertInfoMapper.countBySectionId(sectionId) == beExpertVoteResultMapper.countBySectionId(sectionId, voteType, null)) {
            /*//评审按钮出发的投票操作，专家投票完成需要更新评审状态为3（评审结束）
            if (Constants.TWO == flag) {
                //执行更新操作
                BeSectionInfo beSectionInfo = new BeSectionInfo();
                beSectionInfo.setSeqId(sectionId);
                beSectionInfo.setReviewState(3);
                beSectionInfo.setUpdateTime(DateUtil.now());
                //更新标段评审状态为评审结束
                if (beSectionInfoMapper.updateByPrimaryKeySelective(beSectionInfo) < 1) {
                    throw new Exception("更新标段评审状态失败！");
                }
            }*/
            List<VoteResultDto> list = getVoteResultList(sectionId, voteType);
            Collections.sort(list);
            return !(list.size() >= 2 && (list.get(0).getCount() == list.get(1).getCount()));
        }
        return false;
    }

    /**
     * 判断是否投票结果是否重复，若有重复清除投票结果进行重新投票
     *
     * @param sectionId
     * @return
     * @throws Exception
     */
    @Override
    public Boolean isRepeatedVotes(String sectionId, String voteType) throws Exception {
        //所有专家投票结束后,判读是否有重复票数
        if (beSectionExpertInfoMapper.countBySectionId(sectionId) == beExpertVoteResultMapper.countBySectionId(sectionId, voteType, null)) {
            List<VoteResultDto> list = getVoteResultList(sectionId, voteType);
            Collections.sort(list);
            if (list.size() >= 2 && (list.get(0).getCount() == list.get(1).getCount())) {
                return true;
            }
        }
        return false;
    }

    /**
     * delRepeatedVotes
     * @param sectionId
     * @param voteType
     * @return
     * @throws Exception
     */
    @Override
    public int delRepeatedVotes(String sectionId, String voteType) throws Exception {
        //先将之前的组长改为非组长
        List<BeSectionExpertInfo> experts = beSectionExpertInfoMapper.getExpertManager(sectionId);
        if(experts != null && !experts.isEmpty()) {
            for(BeSectionExpertInfo expert:experts) {
                BeSectionExpertInfo beSectionExpertInfo = new BeSectionExpertInfo();
                beSectionExpertInfo.setSeqId(expert.getSeqId());
                beSectionExpertInfo.setIsManager(Constants.ZERO);
                beSectionExpertInfoMapper.updateByPrimaryKeySelective(beSectionExpertInfo);
            }
        }
        //根据标段id软删除投票结果信息
        return beExpertVoteResultMapper.delBySectionId(sectionId, voteType, null);
    }

    @Override
    public List<Map<String, Object>> getVoteResultDetailList(String sectionId, String voteType, String submitCode) {

        return beExpertVoteResultMapper.getVoteResultDetailList(sectionId, voteType, submitCode);
    }

    @Override
    public BeExpertVoteResult queryResultByExpertId(BeExpertVoteResult beExpertVoteResult) throws Exception {
        return beExpertVoteResultMapper.queryResultByExpertId(beExpertVoteResult);
    }

    @Override
    public int delBySectionId(String sectionId, String voteType, String submitCode) throws Exception {
   
        return beExpertVoteResultMapper.delBySectionId(sectionId, voteType, submitCode);
    }

    @Override
    public String computerVoteResult(String sectionId, String voteType, String submitCode) throws Exception {
        //null表示本次投票还有专家未投票，0、投票多数不同意 1、投票多数同意
        if (beSectionExpertInfoMapper.countBySectionId(sectionId) == beExpertVoteResultMapper.countBySectionId(sectionId, voteType, submitCode)) {
            List<Map<String, Object>> list = beExpertVoteResultMapper.queryVoteResult(sectionId, voteType, submitCode);
            //sql统计的结果已经按票数排序过，直接返回第一条数据的投票结果
            return OConvertUtils.getString(list.get(0).get("voteResult"));
        }
        return "-1";
    }
}
